package com.tlgen.orm.config;

import com.tlgen.orm.components.rest.RestFactoryBean;
import com.tlgen.orm.components.rest.model.RequestMappingClasses;
import com.tlgen.orm.utils.log.ColorLogger;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.autoproxy.AutoProxyUtils;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.AnnotationConfigUtils;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.List;

import static com.tlgen.orm.utils.ClassesUtils.getRequestMappingClassesWithAnnotation;

public class EnhancedImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {

    private static final Logger logger = LoggerFactory.getLogger(EnhancedImportBeanDefinitionRegistrar.class);
    private static final String PROXY_TARGET_ATTRIBUTE =
            AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE;

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
                                        BeanDefinitionRegistry registry) {

        // 1. 获取所有需要注册的REST接口
        List<RequestMappingClasses> requestMappingClasses = getRequestMappingClassesWithAnnotation();
        if (CollectionUtils.isEmpty(requestMappingClasses)) {
            ColorLogger.printInfoMessage(ColorLogger.LIGHTNING + "🔥 No REST interfaces found for dynamic registration");
            return;
        }

        ColorLogger.printInfoMessage(ColorLogger.LIGHTNING + "🚀 Found " + requestMappingClasses.size() + " REST interfaces for registration");

        // 2. 创建并注册Bean定义
        for (RequestMappingClasses mappingClass : requestMappingClasses) {
            try {
                registerRestBean(registry, mappingClass);
            } catch (ClassNotFoundException e) {
                logger.error("Failed to register REST interface: {}", mappingClass.getClassName(), e);
            }
        }

        ColorLogger.printInfoMessage(ColorLogger.LIGHTNING + "🎉 Successfully registered REST interfaces");
    }

    /**
     * 确保自动代理处理器正确处理工厂Bean
     */
    private void markProxyRequirements(BeanDefinitionRegistry registry) {
        // 关键：注册AOP基础设施后处理器
        AnnotationConfigUtils.registerAnnotationConfigProcessors(registry);

        // 确保代理处理器能正确处理工厂Bean
        String[] processorNames = registry.getBeanDefinitionNames();
        for (String name : processorNames) {
            if (name.contains("AutoProxyCreator")) {
                BeanDefinition definition = registry.getBeanDefinition(name);
                definition.setAttribute("earlyProxyInterfaces", Boolean.TRUE);
            }
        }
    }

    /**
     * 注册单个REST接口Bean
     */
    private String registerRestBean(BeanDefinitionRegistry registry,
                                    RequestMappingClasses mappingClass) throws ClassNotFoundException {

        Class<?> restInterface = Class.forName(mappingClass.getClassName());
        String beanName = restInterface.getName();

        // 避免重复注册
        if (registry.containsBeanDefinition(beanName)) {
            logger.warn("⏭️ Interface already registered: {}", beanName);
            return beanName;
        }

        // 构建Bean定义
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(restInterface);
        AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();

        // 指定工厂Bean
        beanDefinition.setBeanClass(RestFactoryBean.class);
        beanDefinition.getPropertyValues().add("restInterface", restInterface.getName());

        // 🔑 关键设置：确保能被自动代理
        beanDefinition.setAttribute(PROXY_TARGET_ATTRIBUTE, Boolean.TRUE);
        beanDefinition.setAttribute("factoryBeanTargetType", restInterface);
        beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);

        // 注册Bean定义
        registry.registerBeanDefinition(beanName, beanDefinition);
        logger.debug("✅ Registered REST interface: [{}]", beanName);

        return beanName;
    }

}